package com.abc.def.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;

public class ProcessUtil {

    /**
     * @param processName
     * @descriotion 结束进程
     */
    public static void closeProcess(String processName) {
        try {
            Runtime.getRuntime().exec("taskkill /F /IM " + processName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void killWithPid(int pid) {
        try {
            Process process = Runtime.getRuntime().exec("taskkill /F /pid " + pid + "");
            InputStream inputStream = process.getInputStream();
            String txt = KillServer.readTxt(inputStream, "GBK");
            System.out.println(txt);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param processName
     * @return
     * @description 判断进程是否运行
     */
    public static boolean processIsRun(String processName) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("tasklist -fi \"imagename eq " + processName + '"');
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (InputStream ins = process.getInputStream();
             InputStreamReader insr = new InputStreamReader(ins, "GBK");
             BufferedReader br = new BufferedReader(insr);) {

            String line = null;
            while ((line = br.readLine()) != null) {
                if (line.contains(processName)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param port
     * @return
     * @description 根据端口获取所有pid
     */
    public static Set<String> getPidsByPort(int port) {
        Process process = null;
        try {
            //查找进程号
            process = Runtime.getRuntime().exec("cmd /c netstat -ano | findstr \"" + port + "\"");
        } catch (IOException e) {
            e.printStackTrace();
        }

        Set<String> pids = new HashSet<>();
        try (InputStream ins = process.getInputStream();
             InputStreamReader insr = new InputStreamReader(ins, "UTF-8");
             BufferedReader br = new BufferedReader(insr);) {
            String line = null;
            while ((line = br.readLine()) != null) {
                if (line.contains(String.valueOf(port))) {
                    System.out.println(line);
                    pids.add(getPid(line));
                }
            }
            return pids;
        } catch (Exception e) {
            e.printStackTrace();
            return pids;
        }
    }

    /**
     * @param line
     * @return
     * @description 获取pid
     */
    private static String getPid(String line) {
        int offset = line.lastIndexOf(" ");
        String spid = line.substring(offset);
        return spid.replaceAll(" ", "");
    }

    /**
     * 用 Java 调用windows系统的exe文件，比如notepad，calc之类
     */
    public static void openWindowsExe() {
        final Runtime runtime = Runtime.getRuntime();
        @SuppressWarnings("unused")
        Process process = null;
        try {
            final String command = "notepad";// 记事本
            process = runtime.exec(command);

        } catch (final Exception e) {
            System.out.println("Error win exec!");
        }
    }

    public static void startBat(String cmd) {
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        try {
            process = runtime.exec("cmd.exe /c start " + cmd);
        } catch (final Exception e) {
            System.out.println("Error win exec!");
        }
    }

    /**
     * 调用其他的可执行文件，例如：自己制作的exe，或是 下载 安装的软件.
     */
    public static void openExe(String exePath) {
        final Runtime runtime = Runtime.getRuntime();
        @SuppressWarnings("unused")
        Process process = null;

        try {
            process = runtime.exec(exePath);
        } catch (final Exception e) {
            System.out.println("Error exec!");
        }
    }

    /**
     * 打开其他任意格式的文件，比如txt,word等
     */
    public static void openFile(String filePath) {
        final Runtime runtime = Runtime.getRuntime();
        @SuppressWarnings("unused")
        Process process = null;
        final String cmd = "rundll32 url.dll FileProtocolHandler file://" + filePath;
        try {
            process = runtime.exec(cmd);
        } catch (final Exception e) {
            System.out.println("Error exec!");
        }
    }

    public static void main(String[] args) {
        System.out.println("hello");
    }
}
